﻿using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using Dict.DataModel;
using System;
using AssetLoad;
namespace Story
{
    public class StoryDialogManager : Fsm.FsmControllerBaseMono<DialogState>
    {
        public StoryDialogHero[] heros;
        public UILabel labelContent;
        public UILabel labelName;
        public UIWidget container;
        public AnimationCurve curveEaseInOut;
        public TweenAction tweenComponent;
        public UITexture bg;

        public UITweener tween;

        public List<TableStoryDialog> listDialogs = new List<TableStoryDialog>();
        public int currentIndex;

        public Action endCallbackHandler;

        public bool usingTmpData = false;

        private bool inited = false;
        private string bgResName = "";

        public override void InitState()
        {
            base.InitState();
            allStates[DialogState.None] = new DialogStateBase(DialogState.None, this);
            allStates[DialogState.Start] = new DialogStateStart(DialogState.Start, this);
            allStates[DialogState.Next] = new DialogStateNext(DialogState.Next, this);
            allStates[DialogState.Content] = new DialogStateContent(DialogState.Content, this);
            allStates[DialogState.Wait] = new DialogStateWait(DialogState.Wait, this);
            allStates[DialogState.Hide] = new DialogStateHide(DialogState.Hide, this);
            allStates[DialogState.End] = new DialogStateEnd(DialogState.End, this);

            SwitchState(DialogState.None);
        }


        public void Show(string id, Action endCallbackHandler)
        {
            if (!inited)
            {
                InitState();
            }

            this.endCallbackHandler = endCallbackHandler;
            listDialogs = new List<TableStoryDialog>();
            if(usingTmpData)
            {
                listDialogs.AddRange(Dict.Blo.DictStoryBlo.GetStoryDialogByStoryId2(id));
            }
            else
            {
                listDialogs.AddRange(Dict.Blo.DictStoryBlo.GetStoryDialogByStoryId(id));
            }

            if (GameConfig.Instance.GetChannelId == ChannelId.Qihu || GameConfig.Instance.GetChannelId == ChannelId.ios360)
            {
                List<TableStoryDialog> removes = new List<TableStoryDialog>();
                foreach (var dia in listDialogs)
                {
                    if (dia.name == "self")
                    {
                        removes.Add(dia);
                    }
                }
                foreach (var dia in removes)
                {
                    listDialogs.Remove(dia);
                }
            }
            
            
            gameObject.SetActive(true);

            
            tween.PlayForward();
            tween.ResetToBeginning();

            labelContent.text = "";
            SwitchState(DialogState.Start);

            StartCoroutine(_Show(tween.duration));
        }
        public IEnumerator _Show(float time)
        {
            yield return new WaitForSeconds(time + 0.5f);
            tween.enabled = false;
            var panel = GetComponent<UIPanel>();
            if (panel != null)
            {
                panel.alpha = 1f;
            }
        }

        public float Hide()
        {
            tween.PlayReverse();
            tween.ResetToBeginning();
            return tween.duration;
        }

        public TableStoryDialog currentDialog
        {
            get
            {
                return listDialogs[currentIndex];
            }
        }

        public DialogStateBase currentDialogState
        {
            get
            {
                return base.currentState as DialogStateBase;
            }
        }

        public void SetName(string name)
        {
            labelName.text = name;
        }

        public void SetText(string text)
        {
            labelContent.text = text;
        }

        public void SetBackGround(string resName)
        {
            if (resName.Equals(bgResName))
            {
                return;
            }
            bgResName = resName;
            bg.mainTexture = GetBGTexture2DFromCache(resName);
        }

        public void PlayAudio(string soundName)
        {
            AudioManager.Instance.Play(soundName);
        }

        void Update()
        {
            UpdateState();
        }

        public void OnStoryClick()
        {
            currentDialogState.Click();
        }

        public void OnSkipClick()
        {
            SwitchState(DialogState.Hide);
        }

        public void Clear()
        {
            foreach (var hero in heros) {
                hero.Clear();
            }
            bg.mainTexture = null;
            bgResName = "";
            listDialogs.Clear();
            currentIndex = 0;
        }

        #region PreLoad
        List<string> InvolveBackgrounds = new List<string>();
        List<string> InvolveDialogHeroIds = new List<string>();
        List<string> InvolveSounds = new List<string>();

        Dictionary<string, Texture2D> bgCache = new Dictionary<string, Texture2D>();
        Dictionary<string, UIAtlas> atlasCache = new Dictionary<string, UIAtlas>();

        public bool isPreloadResourceComplete;

        public void PreLoadResource(LoadCompleteNotify callback) {
            StartCoroutine(_PreLoadResource(callback));
        }

        IEnumerator _PreLoadResource(LoadCompleteNotify callback) {
            isPreloadResourceComplete = false;
            InvolveBackgrounds.Clear();
            InvolveDialogHeroIds.Clear();
            InvolveSounds.Clear();
            foreach (var l in listDialogs) {
                if (!string.IsNullOrEmpty(l.background))
                {
                    if (!InvolveBackgrounds.Contains(l.background))
                    {
                        InvolveBackgrounds.Add(l.background);
                    }
                }
                if (!InvolveDialogHeroIds.Contains(l.heroIds0)) {
                    InvolveDialogHeroIds.Add(l.heroIds0);
                }
                if (!InvolveDialogHeroIds.Contains(l.heroIds1)) {
                    InvolveDialogHeroIds.Add(l.heroIds1);
                }
                if (!InvolveDialogHeroIds.Contains(l.heroIds2)) {
                    InvolveDialogHeroIds.Add(l.heroIds2);
                }
                if (!InvolveDialogHeroIds.Contains(l.heroIds3)) {
                    InvolveDialogHeroIds.Add(l.heroIds3);
                }
                if(!string.IsNullOrEmpty(l.sound))
                {
                    if (!InvolveSounds.Contains(l.sound))
                    {
                        InvolveSounds.Add(l.sound);
                    }
                }
            }

            int taskCount = 0;
            foreach (var bgName in InvolveBackgrounds)
            {
                StartCoroutine(ResourceLoader.GetInstance().textureLoader.LoadTexture(@"juqingbg/" + bgName, () =>
                {
                    taskCount--;
                }));
                taskCount++;
            }

            foreach (var soundName in InvolveSounds)
            {
                StartCoroutine(AudioManager.Instance.LoadAudioResource(soundName, () =>
                {
                    taskCount--;
                }));
                taskCount++;
            }

            List<string> loadedAtlasNames = new List<string>();
            foreach (var id in InvolveDialogHeroIds) {
                string dialogHeroId = id;
                if (id.Equals("self")) {
                    if (StaticData.playerData.isPlayerMan)
                    {
                        dialogHeroId = "self_0";
                    }
                    else {
                        dialogHeroId = "self_1";
                    }
                }

                var tsd = Dict.Blo.DictStoryBlo.GetTableStoryDialoHero(dialogHeroId);
                if (tsd != null)
                {
                    if (!string.IsNullOrEmpty(tsd.faceAtlas))
                    {
                        StartCoroutine(ResourceLoader.GetInstance().atlasLoader.LoadAtlas(tsd.faceAtlas, () =>
                        {
                            taskCount--;
                        }));
                        taskCount++;
                        if (!loadedAtlasNames.Contains(tsd.faceAtlas)) {
                            loadedAtlasNames.Add(tsd.faceAtlas);
                        }
                    }
                    if (!string.IsNullOrEmpty(tsd.bodyAtlas))
                    {
                        string atlasName = tsd.bodyAtlas;
                        StartCoroutine(ResourceLoader.GetInstance().atlasLoader.LoadAtlas(atlasName, () =>
                        {
                            taskCount--;
                        }));
                        taskCount++;
                        if (!loadedAtlasNames.Contains(tsd.bodyAtlas)) {
                            loadedAtlasNames.Add(tsd.bodyAtlas);
                        }
                    }
                }
            }
            while (taskCount > 0) {
                yield return null;
            }

            foreach (var bgName in InvolveBackgrounds) {
                var tex = ResourceLoader.GetInstance().textureLoader.GetTexture(@"juqingbg/" + bgName, bgName) as Texture2D;
                bgCache[bgName] = tex;
            }

            foreach (var atlasName in loadedAtlasNames) {
                var at = ResourceLoader.GetInstance().atlasLoader.GetAtlas(atlasName);
                if (at != null)
                {
                    atlasCache[atlasName] = at;
                }
            }
                
            if (callback != null) {
                callback();
            }
            isPreloadResourceComplete = true;
        }

        public void PreUnloadResoruce() {
            
            foreach (var bg in InvolveBackgrounds)
            {
                ResourceLoader.GetInstance().textureLoader.UnloadTexture(@"juqingbg/" + bg);
            }

            foreach (var id in InvolveDialogHeroIds)
            {
                var tsd = Dict.Blo.DictStoryBlo.GetTableStoryDialoHero(id);
                if (tsd != null)
                {
                    ResourceLoader.GetInstance().atlasLoader.UnloadAtlas(tsd.bodyAtlas);
                    ResourceLoader.GetInstance().atlasLoader.UnloadAtlas(tsd.faceAtlas);
                }
            }
            foreach(var id in InvolveSounds)
            {
                AudioManager.Instance.UnloadAudioResource(id);
            }
            InvolveBackgrounds.Clear();
            InvolveDialogHeroIds.Clear();
            InvolveSounds.Clear();
            bgCache.Clear();
            atlasCache.Clear();
        }

        public Texture2D GetBGTexture2DFromCache(string bgName) {
            if (bgCache != null && bgCache.ContainsKey(bgName)) {
                return bgCache[bgName];
            }
            return null;
        }

        public UIAtlas GetUIAtlasFromCache(string atlasName) {
            if (atlasCache != null && atlasCache.ContainsKey(atlasName)) {
                return atlasCache[atlasName];
            }
            return null;
        }

        #endregion

    }
}
